package com.yootk;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class Account{
    private String name;
    private int asset;
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public Account(String name,int asset){
        this.name = name;
        this.asset = asset;
    }
    public void save(int asset){
        this.readWriteLock.writeLock().lock();
        try{
            this.asset += asset;
            TimeUnit.SECONDS.sleep(1);
            System.out.println("【"+Thread.currentThread().getName()+
                    "】修改银行资产，当前资产为："+this.asset / 100.0);
        }catch (Exception e){
        }finally {
            this.readWriteLock.writeLock().unlock();
        }
}
public String toString(){
        this.readWriteLock.readLock().lock();
        try {
            TimeUnit.MILLISECONDS.sleep(100);
            return "【"+Thread.currentThread().getName()+"】账户名称："+this.name+
                    "、账户余额："+(this.asset / 100.0);
        }catch (Exception e){
            return null;
        }finally {
            this.readWriteLock.readLock().unlock();
        }
    }
}
public class YootkDemo15 {
    public static void main(String [] args)throws Exception{
        Account account = new Account("李兴华",0);
        int money[] = new int[]{100,230,10_000};
        for (int x = 0;x < 10;x++){
            if (x % 2 == 0){
                new Thread(()->{
                    for (int y = 0;y < money.length;y++){
                        account.save(money[y]);
                    }
                },"存款者 - "+ x).start();
            }else {
                new Thread(()->{
                    while (true){
                        System.out.println(account);
                    }
                },"查询者 - " + x).start();
            }
        }
    }
}
